package com.esunrising.esungsc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.common.utils.ESUNGSCUtil;
import com.esunrising.esungsc.common.utils.HttpUtil;
import com.esunrising.esungsc.config.GSCAPIConfig;
import com.esunrising.esungsc.dao.ApiHsdwDao;
import com.esunrising.esungsc.entity.ApiHsdw;
import com.esunrising.esungsc.service.ApiHsdwService;
import com.esunrising.esungsc.service.GSCService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;



@Service
@Slf4j
public class ApiHsdwServiceImpl extends BaseServiceImpl<ApiHsdwDao, ApiHsdw> implements ApiHsdwService {

    @Resource
    private ApiHsdwDao dao;

    @Resource
    private GSCAPIConfig gscapiConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private  GSCService gscService;

    @Resource
    private ApiHsdwService apiHsdwService;

    @Override
    public void syncSave(ApiHsdw entity) {
        // 如果存在，则先删除
        Optional<ApiHsdw> byId = dao.findById(entity.getId());
        byId.ifPresent( doc -> {
            dao.deleteById(doc.getId());
        });
        // 保存数据
        super.save(entity);
    }

    @Override
    public ApiHsdw findById(String id){
        Optional<ApiHsdw> byId = dao.findById(id);
        return byId.orElse(null);
    }

    @Override
    public List<ApiHsdw> getApiFile(String dwbh, String orgCode, String date, String enddate, String hszzid) {

        String orgId = "";
        String ledger = "";
        String type = "pz-test";

        String baseUrl = gscapiConfig.getBaseUrl();
        String getBfLedger = gscapiConfig.getApis().get("getBfLedger");
        String url = baseUrl+getBfLedger;
        //添加query参数
        String uri = HttpUtil.putQueryParam(url, null);
        //添加请求头header参数
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.addAll(new LinkedMultiValueMap<>(gscapiConfig.getRequestHeaders()));

        //添加body请求体参数，
        HashMap<String, Object> bodyHttp = new HashMap<>();
        bodyHttp.put("DATE",date);
        bodyHttp.put("ENDDATE",enddate);
        bodyHttp.put("HSZZID",hszzid);

        //组织参数
        HttpEntity<Map<String,Object>> httpEntity = new HttpEntity<>(bodyHttp,httpHeaders);
        //发送请求
        ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);

        String msg= " ";
        //解析结果
        if (response.getStatusCodeValue() == 200){
            String responeBody = response.getBody();
            System.out.println("@@@@"+responeBody+"@@@@");

            msg = "获取成功";
            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);
            // 更新调用时间记录
            gscService.updateSyncTime(dwbh, orgId, orgCode, ledger, type, LocalDateTime.now());
            return parseBfLedger(responeBody);
        }else {

            // 接口调用失败
            msg = "接口调用失败";
            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);

            System.out.println(response.getStatusCodeValue());
            System.out.println(response.getStatusCode());
            System.out.println(response.getHeaders());
            System.out.println(response.getBody());
            return null;
        }

    }

    @Override
    public void saveApiFile(List<ApiHsdw> apiFile) {
        for(ApiHsdw apiHsdw : apiFile){
            System.out.println("--save--"+apiHsdw+"----");
            apiHsdwService.syncSave(apiHsdw);
        }
    }

    public List<ApiHsdw> parseBfLedger(String jsonStr) {
        // 解析Json字符串
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");//获取字符串
        if(result ) {
            log.info("请求核算账簿数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            List<ApiHsdw> apiHsdwList = new ArrayList<>();
            int bfLedger = value.size();
            for (int i = 0; i < bfLedger; i++) {
                JSONObject element = value.getJSONObject(i);
                ApiHsdw apiHsdw = ESUNGSCUtil.jsonObject2ApiHsdw(element);
                // 加入到apiHsdwList中
                apiHsdwList.add(apiHsdw);
            }

            return apiHsdwList;
        }else{
            log.error("请求核算账簿数据失败");
            return null;
        }
    }
}